import React, { useEffect, useState } from 'react'
import { Button, Form, Input, DatePicker, Select, message, Tag } from 'antd'
import styles from './index.module.scss'
import type { UploadFile } from 'antd/es/upload'
import { patchPersonInfo } from '@/util/request'
import { useAppDispatch, useAppSelector } from '@/store'
import { select_user_info } from '@/store/slice/user/select'
import { get_menu_async, get_user_info_async } from '@/store/slice/user/request'
import { AxiosResData } from '@/util/http'

import dayjs from 'dayjs'
import { useNavigate } from 'react-router-dom'
import { eduOptions, roleOptions } from './constant'
import { PersonInfoFieldType, RoleType } from './interface'
import { imgUrl } from '@/util/constant'
import YuUpload from '@/common_components/upload'
import { roleTagColor, roleToChinese } from './constant'

// 个人信息组件
export default function PersonInfo() {
  // 用户信息
  const personInfo = useAppSelector(select_user_info)
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const dispatch = useAppDispatch()

  // 后端返回图片时的展示
  const [fileList, setFileList] = useState<UploadFile[]>([])

  // 是否为编辑状态
  const IS_EDIT = personInfo?.has_person_info

  // 用户信息回显
  useEffect(() => {
    // 如果是编辑个人用户信息
    if (personInfo?.has_person_info) {
      form.setFieldsValue({ ...personInfo, graduation_time: dayjs(personInfo.graduation_time) })

      const avatar = personInfo.avatar

      // 设置图片的信息
      setFileList([
        {
          uid: avatar,
          name: avatar,
          status: 'done',
          url: imgUrl + avatar
        }
      ])
    }
  }, [personInfo])

  // 图片上传
  const handleChange = (fileList: any[]) => {
    console.log(fileList)
    setFileList(fileList)
  }

  // 表单提交
  const onFinish = async (values: any) => {
    const new_value = { ...values, avatar: values.avatar[0].uid }
    const res: AxiosResData = await patchPersonInfo(personInfo._id, new_value)
    console.log(res)
    console.log('=======')
    if (res.data.code === 200) {
      const user_info: any = await dispatch(get_user_info_async())
      await dispatch(get_menu_async())
      message.success('录入成功')
      // 判断权限是否是student
      if (user_info.payload.role === 'student') {
        navigate('/exam_select')
      } else if (user_info.payload.role === 'admin') {
        navigate('/corret_exam_list')
      } else {
        navigate('/super_admin_home')
      }
    } else {
      message.error('录入失败')
    }
  }

  // 返回上一页
  const goBack = () => {
    navigate(-1)
  }

  return (
    <div className={styles.person_info}>
      <div className={styles.title}>
        {IS_EDIT ? (
          <span className={styles.blue}>个人中心</span>
        ) : (
          <>
            欢迎进入<span className={styles.blue}>请填写个人信息</span>
          </>
        )}
      </div>
      <div className={styles.form}>
        <Form name="basic" form={form} labelAlign="left" labelCol={{ span: 3 }} wrapperCol={{ span: 12 }} style={{ maxWidth: 600 }} initialValues={{ remember: true }} onFinish={onFinish} autoComplete="off">
          <Form.Item<PersonInfoFieldType> label="头像" name="avatar">
            <YuUpload sort="avatar" fileList={fileList} onChange={handleChange}></YuUpload>
          </Form.Item>

          <Form.Item<PersonInfoFieldType> label="花名" name="name" rules={[{ required: true, message: '请输入花名!' }]}>
            <Input />
          </Form.Item>
          {/* 
          <Form.Item<PersonInfoFieldType> label="当前薪资" name="money" rules={[{ required: true, message: '请输入当前薪资!' }]}>
            <Input />
          </Form.Item> */}

          <Form.Item<PersonInfoFieldType> label="技术栈" name="techStack" rules={[{ required: true, message: '请输入技术栈!' }]}>
            <Input />
          </Form.Item>

          <Form.Item<PersonInfoFieldType> label="学历" name="edu" rules={[{ required: true, message: '请输入学历!' }]}>
            <Select
              style={{ width: 120 }}
              options={eduOptions.map((item: string) => {
                return {
                  label: item,
                  value: item
                }
              })}
            />
          </Form.Item>

          {/* 如果是编辑状态就为tag标签展示,只有注册才能选择权限 */}
          <Form.Item<PersonInfoFieldType> label="权限" name="role" rules={[{ required: true, message: '请选择权限' }]}>
            {IS_EDIT ? (
              <Tag color={roleTagColor[personInfo?.role as keyof typeof roleTagColor]}>{roleToChinese[personInfo?.role as keyof typeof roleToChinese]}</Tag>
            ) : (
              <Select
                style={{ width: 120 }}
                options={roleOptions.map((item: RoleType) => {
                  return {
                    label: item.label,
                    value: item.value
                  }
                })}
              />
            )}
          </Form.Item>

          <Form.Item<PersonInfoFieldType> label="毕业时间" name="graduation_time" rules={[{ required: true, message: '请选择毕业时间!' }]}>
            <DatePicker placeholder="请选择毕业时间" />
          </Form.Item>

          <Form.Item<PersonInfoFieldType> label="微信" name="vChat" rules={[{ required: true, message: '请输入微信!' }]}>
            <Input />
          </Form.Item>

          <Form.Item>
            {IS_EDIT ? (
              <>
                <Button style={{ width: 100, marginRight: 60 }} size="large" type="primary" htmlType="submit">
                  确认修改
                </Button>
                <Button style={{ width: 100 }} onClick={goBack}>
                  返回
                </Button>
              </>
            ) : (
              <Button style={{ width: 200 }} size="large" type="primary" htmlType="submit">
                保存信息
              </Button>
            )}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
